﻿var fromPrice = 0;var toPrice = 100000000;
//#region fuctions--------------------------------------------------

function InitResource() {
    $('#wrapperMenu').html(hachimenu);
    $('#cartInfo').html(lang_cartInfo);
    $('#uniqueproducts').html(lang_uniqueproducts);
    $('#interestinglyinday').html(lang_interestinglyinday);
    $('#productcategory').html(lang_productcategory);
    $('#poll').html(lang_poll);
    $('#promotions').html(lang_promotions);
    $('#newArrivals').html(lang_newArrivals);
    $('#recentInfo').html(lang_recentInfo);
    $('#searchcontrol').html("<input id='txtSearch' class='TimKiemTextBox' type='text' value='" + lang_search + "' onfocus=\"if (this.value=='" + lang_search + "') this.value='';\"  onblur=\"if (this.value=='') this.value='" + lang_search + "';\" />");
    
    
    $('#btn_loginUser').html(lang_login);
    $('#btn_createUser').html(lang_registry);
    $('#dialog-form-loginUser-lblUser').html(lang_username);
    $('#dialog-form-loginUser-lblPassword').html(lang_password);
    $('#dialog-form-loginUser-btnSubmit').val(lang_login);
    $('#dialog-form-loginUser-forgotPass').html(lang_forgotpass);
    $('#dialog-form-loginUser-reg').html(lang_registry);
    $('#loggedinLogoutCmd').html(lang_logout);
    $('#dialog-form-addToCart-lblQuantity').html(lang_enterQuantity);
    $('#dialog-form-addToCart-lblQuantityExist').html(lang_QuantityExist);
    $('#dialog-form-addToCart-btnAddToCart').html(lang_addtocartbtn);
    $('#dialog-form-addToCart-btnCancel').html(lang_cancelbtn);
    $('#dialog-form-addToCart').attr("title", lang_addtocart);
    $('#btnMorePage').html(lang_More);
    $('#lblProductDetailInfo').html(lang_ProductDetailInfo);

    $('#productinfodetail_code').html(lang_productCode);
    $('#productinfodetail_Origin').html(lang_productOrigin);
    $('#productinfodetail_Material').html(lang_productMaterial);
    $('#productinfodetail_Size').html(lang_productSize);
    $('#btnAddProductToCart').html(lang_addtocart);
    $('#productinfodetail_Quantity').html(lang_enterQuantity);
    $('#productinfodetail_Price').html(lang_productPrice);
    $('#lblProductGuide').html(lang_productGuide);
    $('#lblProductIntro').html(lang_productIntro);
    $('#lblProductNews').html(lang_productNews);
    $('#lblShowCommentForm').html(lang_productCommentFormCall);
    $('#btnShowCommentForm').html(lang_commentFormLink);
    $('#lblCommentHeader').html(lang_productCommentHeader);
    $('#btnLoadMoreComment').html(lang_moreComment);
    $('#lblSameProducts').html(lang_SameProducts);
    $('#lblSeeMoreSaleItem').html(lang_SeeMoreSaleItem);
    $('#lblSeeMoreNewItem').html(lang_SeeMoreNewItem);
    $('#lblOnlineSupport').html(lang_onlineSupport);
    $('#hotlineNumber').html(lang_hotlineNumber);
    $('#dialog-form-comment-btnSubmit').html(lang_Send);
    $('#dialog-form-comment').attr("title", lang_commentHeader);
    $('#dialog-form-comment-txtTieuDe').attr("defaultvalue", lang_commentTitle);
    $('#dialog-form-comment-txtHoTen').attr("defaultvalue", lang_commentName);
    $('#dialog-form-comment-txtEmail').attr("defaultvalue", lang_commentEmail);
    $('#dialog-form-comment-txtNoiDung').attr("defaultvalue", lang_commentDetail);

    $('#lblFilterByPrice').html(lang_FilterByPrice);
    $('#lblPriceLessThan50').html(lang_PriceLessThan50);
    $('#lblPriceF50To200').html(lang_PriceF50To200);
    $('#lblPriceF200To500').html(lang_PriceF200To500);
    $('#lblPriceGreaterThan500').html(lang_PriceGreaterThan500);
    $('#lblPriceAll').html(lang_PriceAll);
    $('#btnMorePromotionPage').html(lang_MorePromotionPage);
    $('#lblTopicalProducts').html(lang_TopicalProduct);
    $('#lblPromotion').html(lang_promotions);
    $('#lblRecommendedProducts').html(lang_RecommendedProduct);
    $('#lblUniqueProducts').html(lang_uniqueProducts);
    $('#lblproductinfodetail_Quantity').html(lang_lblproductinfodetail_Quantity);
    $('#lnkYahoo').attr('href',lang_yahoosupportlink);
    $('#lnkSkype').attr('href',lang_skypesupportlink);

}
function isValidEmailAddress(emailAddress) {
    var pattern = new RegExp(/^(("[\w-+\s]+")|([\w-+]+(?:\.[\w-+]+)*)|("[\w-+\s]+")([\w-+]+(?:\.[\w-+]+)*))(@((?:[\w-+]+\.)*\w[\w-+]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][\d]\.|1[\d]{2}\.|[\d]{1,2}\.))((25[0-5]|2[0-4][\d]|1[\d]{2}|[\d]{1,2})\.){2}(25[0-5]|2[0-4][\d]|1[\d]{2}|[\d]{1,2})\]?$)/i);
    return pattern.test(emailAddress);
};
function isValidDate(Value) {
    var isValid = true;
    try { jQuery.datepicker.parseDate("yy-mm-dd", Value, null); }
    catch (error) {
        isValid = false;
    }
    return isValid;
}
function isValidDayOfBirth(Value) {
    var isValid = true;
    try {
        var currentYear = (new Date).getFullYear();
        var memyear = jQuery.datepicker.parseDate("yy-mm-dd", Value, null).getFullYear();
        if (currentYear - memyear >= 90 || currentYear - memyear <= 5) { isValid = false; }
    }
    catch (error) {
        isValid = false;
    }
    return isValid;
}
function isNullOrEmpty(value) {
    if (value.replace(/ /gi, "") == "") {
        return true;
    }
    else
        return false;
}

function addToCartAction() {
    var itemid = $('#dialog-form-addToCart-btnAddToCart').attr('productid');
    var orderquantity = parseInt($('#dialog-form-addToCart-txtQuantity').val(), 10);
    var ordermax = parseInt($('#dialog-form-addToCart-txtQuantity').attr('maxlength'), 10);
    if (orderquantity > 0 && orderquantity <= ordermax) {
        $.get('usercontrols/AddToCart.aspx?pid=' + itemid + '&q=' + orderquantity, function (data) {
            if (data > 0) {
                $('#iconcartItemcount').html(data);
                $('#cartItemcount').html(data);
                $('#dialog-form-addToCart').dialog('close');
                $('#dialog-form-addToCart-txtQuantity').val(1);
            }
            else {
                alert(data);
            }
        });
    }
    else {
        alert(lang_OrderQuantityIsNotValid);
    }
}
function logoutaction() {
    var d = new Date();
    $.get('usercontrols/Login.aspx?o=' + d, function (data) {
        loadMemberLoginStatus();
    });
}
function loginaction() {
    var purl = domain + 'usercontrols/Login.aspx/sli';
    var pdata = "{ 'us': '" + $('#dialog-form-loginUser-txtUser').val() + "', 'pa': '" + $('#dialog-form-loginUser-txtPassword').val() + "' }";
    $.ajax({
        type: "POST",
        url: purl,
        data: pdata,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (result) {
            var data = result.d;
            if (data == 'Loggedin') {
                $('#dialog-form-loginUser').dialog('close');
                loadMemberLoginStatus();
            }
            else if (data == 'Null') {
                alert(lang_UserNameNotExist);
            }
            else if (data == 'IsLockedOut') {
                alert(lang_UserIsLockedOut);
            }
            else if (data == 'WrongPass') {
                alert(lang_UserWrongPass);
            }
        }
    });

    return false;
}
function ReloadUserCP() {
    if (userlogged == true) {
        $('#dialog-form-comment-txtHoTen').val(userUserName);
        $('#dialog-form-comment-txtEmail').val(userEmail);

        $("#dialog-form-comment-txtHoTen").attr("disabled", "disabled");
        $("#dialog-form-comment-txtEmail").attr("disabled", "disabled"); 

        $('#loggedinUserName').html(userUserName);
        $('#loggedinUserName').attr('title', userEmail);
        $('#loggedinUserName').attr('href', 'UserCP.aspx?u=' + userUserName);
        $('#loggedout').css('display', 'none');
        $('#loggedin').fadeIn();
        //Check task to do
        if (task == "PostComment") {
            PostComment();
            task == "none";
        }
    }
    else {
        
        $("#dialog-form-comment-txtHoTen").removeAttr("disabled");
        $("#dialog-form-comment-txtEmail").removeAttr("disabled");

        $('#loggedout').fadeIn();
        $('#loggedin').css('display', 'none');
    }
    
    
}
function loadMemberLoginStatus() {
    $.getScript('usercontrols/currentuser.aspx', function (data, textStatus) {
        ReloadUserCP()
    });
}
function getjson(URL, SelectorHolder, pdata) {
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: URL,
        data: pdata,
        //data: "{}",
        dataType: "json",
        success: function (msg) {
            bindProductList(eval(msg.d), SelectorHolder, false);
            PositionChange();
        }
    });
}
function getjsonList(URL, pdata, todo) {
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: URL,
        data: pdata,
        //data: "{}",
        dataType: "json",
        success: function (msg) {
            if (todo == "getComment")
                getComment(eval(msg.d));
            else if (todo == "PromotionsGet")
                PromotionsGet(eval(msg.d));
            else if (todo == "PromotionsCount") 
            {
                totalPromotion = parseInt(eval(msg.d));
                if (totalPromotionVisible >= totalPromotion) {
                    $('#btnMorePromotionPage').html(lang_NoMore);
                }
            }

        }
    });
}

function bindProductList(data, selectorHolder, delbtn) {
    var c = data;
    if (c != null) {
        for (var i = 0; i < c.length; i++) {
            var item = "<div class='item' quantity = '" + c[i].Quantity + "' productid='" + c[i].ProductID + "' >";
            if (delbtn == true)
                item += "<a href='javascript:delRecentViewItem(" + c[i].ProductID + ")' class='delRecentItem'></a>";

            item += "<div class='iconHolder'>";
            
            
            if (c[i].IsRecommended == true)
                item += "<div class='Recommendedicon'></div>";
            if (c[i].IsUnique == true)
                item += "<div class='uniqueicon'></div>";
            if (c[i].IsTopical == true)
                item += "<div class='TopicalProductIcon'></div>";
            if (c[i].IsSaleOff == true)
                item += "<div class='saleicon'></div>";
            if (c[i].IsNew == true)
                item += "<div class='newicon'></div>";
            item += "</div>";

            if (c[i].Quantity > 0)
                item += "<a href='#addtocart' title='" + lang_addtocart + "' class='itemAddToCart'></a>";
            else
                item += "<a href='#" + lang_OutOfStock + "' title='" + lang_OutOfStock + "' class='itemAddToCartDisable'></a>";
            item += "<a title='" + c[i].ProductName + "' href='" + domain + c[i].Alias + "'><div><img class='itemImage' alt='" + c[i].ProductName + "' src='upload/products/small/" + c[i].DisplayCode + ".jpg' /></div>";
            item += "<span class='itemName'>" + c[i].ProductName + "</span></a>";
            if (c[i].IsSaleOff == true)
                item += "<p class='oldPrice'>" + c[i].Price + "</p><p class='NewPrice'>" + c[i].PriceSaleOff + "</p></div>";
            else
                item += "<p class='oldPrice'> </p><p class='NewPrice'>" + c[i].Price + "</p></div>";
            
            $(selectorHolder).append(item);
        }
        initAddToCartDialog();
    }

}
function delRecentViewItemActionBiding() {
    $('.delRecentItem').click(function () {
        $(this).parent().fadeOut();
        delRecentViewItem($(this).parent().attr('productid'));
    });

}
function delRecentViewItem(pItemID) {
    $.get('usercontrols/RecentViewItem.aspx?cmd=del&pid=' + pItemID, function (data) {
        getRecentViewItem();
    });
}
function getRecentViewItem() {

    $('#RecentListHolder').css('display', 'none');
    var d = new Date();
    $.get('usercontrols/RecentViewItem.aspx?cmd=count&time=' + d, function (data) {

        $('#RecentList').html('');
        if (parseInt(data, 10) != 0) {
            $('#recentitemcount').html(' (' + data + ')');
            $.ajax({
                type: "GET",
                contentType: "application/json; charset=utf-8",
                url: 'usercontrols/RecentViewItem.aspx?cmd=getItemInrecentview&time=' + d,
                data: '{}',
                dataType: "json",
                success: function (msg) {
                    bindProductList(eval(msg), '#RecentList', true);
                    if ($('#RecentList').html() != '')
                        $('#RecentListHolder').css('display', 'block');
                    delRecentViewItemActionBiding();
                }
            });
        }
    });

}
function innitDefaultValueWhenNull(id) {
    $('#' + id).val($('#' + id).attr("defaultvalue"));
    $('#' + id).live('focus', function () {
        if (this.value == $(this).attr("defaultvalue")) this.value = '';
    });
    $('#' + id).live('blur', function () {
        if (this.value == '') this.value = $(this).attr("defaultvalue");
    });
}
function preloadImages() {
    for (var i = 0; i < arguments.length; ++i)
        (preloadImages.store[preloadImages.store.length] = new Image()).src = arguments[i];
}
function initAddToCartDialog() {
    $("#dialog-form-addToCart:ui-dialog").dialog("destroy");
    $("#dialog-form-addToCart").dialog({
        autoOpen: false, position: 'center', resizable: false, draggable: false, height: 200, width: 390, modal: true
    });
    $(".itemAddToCart").click(function () {
        $("#dialog-form-addToCart-item").html($(this).parent().html());
        var quantity = $(this).parent().attr('quantity');
        $('#dialog-form-addToCart-btnAddToCart').attr('productid', $(this).parent().attr('productid'));
        $('#dialog-form-addToCart-txtQuantityExist').html(quantity);
        $('#dialog-form-addToCart-txtQuantity').attr('maxlength', quantity);
        $("#dialog-form-addToCart").dialog("open");
    });
    $("#dialog-form-addToCart-btnCancel").click(function () {
        $("#dialog-form-addToCart").dialog("close");
    });
}
function initCommentDialog() {
    
    $("#dialog-form-comment:ui-dialog").dialog("destroy");
    $("#dialog-form-comment").dialog({
        autoOpen: false, position: 'center', resizable: false, draggable: false, height: 200, width: 390, modal: true
    });
    $("#btnShowCommentForm, #productRateVote").click(function () {
        $("#dialog-form-comment").dialog("open");
    });
    $("#dialog-form-comment-btnCancel").click(function () {
        $("#dialog-form-comment").dialog("close");
    });
}
function PostComment() {
    var cd = $('#dialog-form-comment-txtNoiDung').val();
    if (cd == lang_commentDetail) {
        alert(lang_commentValidateNullDetail.format((userUserName == "" ? lang_userNameDefault : userUserName)));
        return;
    }
    var purl = domain + 'usercontrols/Webkit.aspx/PostProductComment';
    var pdata = "{ 'pProductID': '" + cProductID +
                                    "', 'pComment': '" + $('#dialog-form-comment-txtNoiDung').val() +
                                    "' , 'Vote':'" + $('#dialog-form-comment-txtStar').attr('star') + "' }";
    $.ajax({
        type: "POST",
        url: purl,
        data: pdata,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (result) {
            var data = result.d;
            if (data == 'Posted') {
                $('#dialog-form-comment').dialog('close');
                alert(lang_commentPosted.format(userUserName));
                $('#dialog-form-comment-txtNoiDung').val('');
                $('#dialog-form-comment-txtStar').attr('star', 0);
            }
            else if (data == 'PleaseLogin') {
                $("#dialog-form-loginUser").dialog("open");
                task = "PostComment";
            }
            else {
                alert(data);
            }
        }
    });
}
function PositionChange() {
    var cyindex = $(window).scrollTop();
    var divheight = $("#CategoryMenu").height();
    var documentheight = $(document).height();
    var winheight = $(window).height();
    var headerHeight = $("#bodyHolder").offset().top;
    var footerHeight = documentheight - $("#bodyHolder").height() - headerHeight;


    if (cyindex > 0) {
        if ($('#CategoryMenu').height() < $("#bodyHolder").height()) {
            $('#top').fadeIn();
            if (cyindex <= headerHeight) {
                $("#CategoryMenu").attr("class", "LeftCatogory");
            }
            else if (cyindex > headerHeight && ((documentheight - cyindex) - divheight) > footerHeight) {
                $("#CategoryMenu").attr("class", "fixObsoluteLeftCatogory");
            }
            else {
                $("#CategoryMenu").attr("class", "fixBottomLeftCatogory");
            }
        } else {
            $("#CategoryMenu").attr("class", "LeftCatogory");
        }

    }
    else {
        $('#top').fadeOut();
    }
}
function createSlideShow(pSlideShowCategoryID, pSelector, pEffect) {
    var URL = domain + "services/WebService.asmx/GetSlideShow";
    var pdata = '{SlideShowCategoryID: ' + pSlideShowCategoryID + ', Lang: "' + lang + '"}';
    var strSliderItems = "";
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: URL,
        data: pdata,
        dataType: "json",
        success: function (msg) {
            var c = eval(msg.d);
            for (var i = 0; i < c.length; i++) {
                strSliderItems += "<a href='" + c[i].Link + "'><img src='" + c[i].Image + "' alt='" + c[i].Title + "' /></a>";
            }
            $(pSelector).html(strSliderItems);
            if (pEffect == "" || pEffect == undefined)
                $(pSelector).nivoSlider();
            else
                $(pSelector).nivoSlider({ effect: pEffect });
        }
    });
}
function setFilterOptionActive(selector) {
    $('.FilterOption .active').removeClass('active');
    $(selector).addClass('active');
}


function loadAllPage(pCategoryID) {
    var URL = "services/WebService.asmx/CountProductByCategoryID";
    var pdata = '{CategoryID: ' + pCategoryID + ', Lang: "' + lang + '", FromPrice: ' + fromPrice + ', ToPrice: ' + toPrice + '}';

    if (pCategoryID == -1) {
        URL = "services/WebService.asmx/CountNewProduct";
        pdata = '{ Lang: "' + lang + '", FromPrice: ' + fromPrice + ', ToPrice: ' + toPrice + '}';
    }
    else if (pCategoryID == -3 || pCategoryID == -2)
    {
        URL = "services/WebService.asmx/ProductTypeProductsCount";
        pdata = '{ ProductTypeID: "' + pCategoryID*(-1) + '", FromPrice: ' + fromPrice + ', ToPrice: ' + toPrice + '}';
    }
    else if (pCategoryID == -99999) {
        URL = "http://localhost:15732/services/WebService.asmx/SearchProductsCount";
        pdata = '{ Key: "' + searchKey + '", FromPrice: ' + fromPrice + ', ToPrice: ' + toPrice + '}';
    }
    
    var strPageItems = "";
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: URL,
        data: pdata,
        dataType: "json",
        success: function (msg) {
            var r = parseInt(eval(msg.d), 10);
            var c = parseInt(r / conf_PageSize);
            if ((c * conf_PageSize) < r)
                c++;
            
            $('#txtGoToPage').attr('maxlength', c);
            $('#lblPagging').html(lang_Pagging.format(c.toString()));
            pageCount = c;
            if (c > 0) {
                for (var i = 1; i <= c; i++)
                    strPageItems += "<div style='display:none' id='listItemPage" + i + "'><a href='javascript:loadPage(" + i + ", cCategoryID);' class='pageindex' id='Page" + i + "'>" + lang_Page + " " + i + "</a><div id='divli" + i + "'></div></div>";
            }
            else {
                strPageItems = lang_NoProductFoundInCate;
                $('#btnMorePage').html(lang_HaveNoPage);
            }
            if (pCategoryID == -1) {
                $('#HangMoiVeList').html(strPageItems);
                loadPage(1, -1);
            }
            else {

                $('#listItem').html(strPageItems);
                loadPage(1, pCategoryID);
                loadPage(2, pCategoryID);
            }
        }
    });
}
function loadPage(pPage, pCategoryID) {
    pPage = parseInt(pPage, 10);
    cpage = pPage + 1;
    $('#listItemPage' + pPage).fadeIn();
    if ($('#divli' + pPage).html() != '') {
        $('#divli' + pPage).toggle();
    }
    else if (!isNaN(pPage)) {
        var pSkip = (pPage - 1) * 12;
        if (pCategoryID==-1) {
            getjson("services/WebService.asmx/GetNewProducts", '#divli' + pPage, '{ Lang: "' + lang + '", Take:' + conf_PageSize + ', Skip:' + pSkip + ', FromPrice:' + fromPrice + ', ToPrice:' + toPrice + ' }');
        }
        else if (pCategoryID == -3 || pCategoryID == -2)
        {
            getjson("services/WebService.asmx/ProductTypeGetProducts", '#divli' + pPage, '{ProductTypeID: ' + (-1)*pCategoryID + ', Lang: "' + lang + '", Take:' + conf_PageSize + ', Skip:' + pSkip + ', FromPrice:' + fromPrice + ', ToPrice:' + toPrice + ' }');
        }
        else if (pCategoryID == -99999) {
            getjson("http://localhost:15732/services/WebService.asmx/SearchGetProducts", '#divli' + pPage, '{Key: "' + searchKey + '", Lang: "' + lang + '", Take:' + conf_PageSize + ', Skip:' + pSkip + ', FromPrice:' + fromPrice + ', ToPrice:' + toPrice + ' }');
        }
        else
            getjson("services/WebService.asmx/GetProductsByCategoryID", '#divli' + pPage, '{CategoryID:' + cCategoryID + ', Lang: "' + lang + '", Take:' + conf_PageSize + ', Skip:' + pSkip + ', FromPrice:' + fromPrice + ', ToPrice:' + toPrice + ' }');
    }
    PositionChange();
    if (pageCount == 0)
        $('#btnMorePage').html(lang_HaveNoPage);
    else if (pPage >= pageCount)
        $('#btnMorePage').html(lang_NoMore);
    else
        $('#btnMorePage').html(lang_More);
}
//#endregion

$(document).ready(function () {
    loadMemberLoginStatus();
    InitResource();
    $('#leftPanel').html(hachicategorymenu);

    //#region accordion cate
    $(function () {
        $("#accordion").accordion({
            event: "click ", //hoverintent
            autoHeight: false,
            animated: "bounceslide", //easeslide
            navigation: true,
            alwaysOpen: false,
            active: false,
            collapsible: true
        })
        ;
    });
    //#endregion

    //#region scroll event
    $(window).scroll(function () {
        PositionChange();
    });
    //#endregion

    //#region remove outline
    if (document.documentElement.attachEvent)
        document.documentElement.attachEvent('onmousedown', function () {
            event.srcElement.hideFocus = true
        });
    //#endregion

    //#region go to page key enter press event
    $(".gotoPage").keyup(function (event) {
        var inputv = $(this).val();
        if (event.keyCode == 13) {
            var pPage = parseInt(inputv);
            if (!isNaN(pPage)) {
                try {
                    loadPage(pPage, cCategoryID)
                    $('html, body').animate({ scrollTop: $('#Page' + pPage).offset().top }, 500);
                } catch (e) {

                }

            }
            return false;
        }
    });
    //#endregion

    //#region Recent items
    getRecentViewItem();
    //#endregion

    //#region validate number input
    $(".validateNum").keypress(function (event) {
        var e = event || evt; // for trans-browser compatibility
        var f = parseInt($(this).val() + String.fromCharCode(e.keyCode), 10);
        var max = parseInt($(this).attr('maxlength'), 10);
        if (!isNaN($(this).val() + String.fromCharCode(e.keyCode)) && f >= 0 && f <= max)
            return true;
        else
            return false;
    });
    //#endregion

    //#region login dialog
    $("#dialog-form-loginUser:ui-dialog").dialog("destroy");
    $("#dialog-form-loginUser").dialog({
        autoOpen: false, position: 'center', resizable: false,
        draggable: false, height: 200, width: 390, modal: true
    });
    $("#btn_loginUser").click(function () {
        $("#dialog-form-loginUser").dialog("open");
    });
    //#endregion

    //#region add to cart
    initAddToCartDialog();
    //#endregion

    //#region show current user
    ReloadUserCP();
    //#endregion

    //#region load cart
    $.get('usercontrols/AddToCart.aspx?cmd=count', function (data) {
        if (data > 0) {
            $('#iconcartItemcount').html(data);
            $('#cartItemcount').html(data);
        }
    });
    //#endregion

    //#region footer  init
    $('#page_footer').html(pageFooter);
    $('#pageall').append('<div id="top">Back to Top</div>');
    $('#top').click(function () {
        $('html, body').animate({ scrollTop: 0 }, 300);
    });
    //#endregion

    //#region recent dialog
    $("#dialog-form-RecentView:ui-dialog").dialog("destroy");
    $("#dialog-form-RecentView").dialog({
        autoOpen: false, position: 'center', resizable: false, draggable: false, show: 'slide',
        height: 500, width: 680, modal: true, dialogClass: 'dialog-form-RecentView'
    });
    $('#btnShowAllRecentViewItem').click(function () {

        $("#dialog-form-RecentView").dialog("open");
        $('#dialogForm_RecentList').html('Loading...');
        $.ajax({
            type: "GET",
            contentType: "application/json; charset=utf-8",
            url: 'usercontrols/RecentViewItem.aspx?cmd=getAllItemInrecentview&time=' + d,
            data: '{}',
            dataType: "json",
            success: function (msg) {
                $('#dialogForm_RecentList').html('');
                bindProductList(eval(msg), '#dialogForm_RecentList', true);
                if ($('#dialogForm_RecentList').html() == '')
                    $('#dialogForm_RecentList').html('no item found');
                delRecentViewItemActionBiding();
            }
        });

        //fillter price


    });
    //#endregion

    //#region QR code
    $("#dialog-form-QRCode:ui-dialog").dialog("destroy");
    $("#dialog-form-QRCode").dialog({
        autoOpen: false, position: 'center', resizable: false, draggable: false, show: 'slide',
        height: 200, width: 390, modal: true, dialogClass: 'dialog-form-QRCode'
    });
    $('#btnQRCodeShow').click(function () {
        $("#dialog-form-QRCode").dialog("open");
        if ($("#QRCodeHolder").html() == "") {
            $("#QRCodeHolder").QRCode(location.href, { width: 150, height: 150 });
        }
    });
    $("#QRCodeHolder").QRCode(location.href, { width: 150, height: 150 });
    //#endregion

    //#region Comment
    initCommentDialog();
    $('#dialog-form-comment-btnSubmit').click(function () {
        PostComment();
    });
    innitDefaultValueWhenNull('dialog-form-comment-txtTieuDe');
    innitDefaultValueWhenNull('dialog-form-comment-txtHoTen');
    innitDefaultValueWhenNull('dialog-form-comment-txtEmail');
    innitDefaultValueWhenNull('dialog-form-comment-txtNoiDung');
    //#endregion

    //#region Search
    $('#txtSearch').keypress(function (event) {
        var keycode = (event.keyCode ? event.keyCode : event.which);
        if (keycode == '13') {
            var url = '/title/' + $(this).val().replace(/ /gi, "+");
            if (url != '/title/')
                document.location.href = url;
        }
        event.stopPropagation();
        
    });
    //#endregion

});

String.prototype.format = function () {
    var formatted = this;
    for (var i = 0; i < arguments.length; i++) {
        var regexp = new RegExp('\\{' + i + '\\}', 'gi');
        formatted = formatted.replace(regexp, arguments[i]);
    }
    return formatted;
};
preloadImages.store = [];
preloadImages("imgs/HachiLogo.gif", "imgs/Big-bg.jpg");
//QR code
(function () { $.fn.QRCode = function (a, b) { var c = { width: 150, height: 150 }; if (b) { $.extend(c, b) } this.each(function () { $(this).append("<img src='https://chart.googleapis.com/chart?cht=qr&chs=" + c.width + "x" + c.height + "&chl=" + escape(a) + "' alt='QR Code' />") }) } })(jQuery);


//(function (a) { a.fn.parallax = function (b) { var b = a.extend({ useHTML: true, elements: [] }, b || {}); a((b.useHTML) ? "html" : this).mousemove(function (k) { var g = a(this); var d = { x: Math.floor(parseInt(g.width()) / 2), y: Math.floor(parseInt(g.height()) / 2) }; var l = { x: (k.pageX - g.offset().left), y: (k.pageY - g.offset().top) }; var h = { x: (l.x - d.x), y: (l.y - d.y) }; for (var j = b.elements.length - 1; j >= 0; j--) { var c = {}, m, f; for (var n in b.elements[j].properties.x) { f = b.elements[j].properties.x[n]; m = f.initial + (h.x * f.multiplier); if ("min" in f && m < f.min) { m = f.min } else { if ("max" in f && m > f.max) { m = f.max } } if ("invert" in f && f.invert) { m = -(m) } if (!("unit" in f)) { f.unit = "px" } c[n] = m + f.unit } for (var n in b.elements[j].properties.y) { f = b.elements[j].properties.y[n]; m = f.initial + (h.y * f.multiplier); if ("min" in f && m < f.min) { m = f.min } else { if ("max" in f && m > f.max) { m = f.max } } if ("invert" in f && f.invert) { m = -(m) } if (!("unit" in f)) { f.unit = "px" } c[n] = m + f.unit } if ("background-position-x" in c || "background-position-y" in c) { c["background-position"] = "" + (("background-position-x" in c) ? c["background-position-x"] : "0px") + " " + (("background-position-y" in c) ? c["background-position-y"] : "0px"); delete c["background-position-x"]; delete c["background-position-y"] } a(b.elements[j].selector).css(c) } }) } })(jQuery);
//$('#parallaxHeader1').parallax({
//    'elements': [{
//        'selector': '#parallaxHeader',
//        'properties': {
//            'x': {
//                'background-position-x': {
//                    'initial': 0,
//                    'multiplier': 0.1,
//                    'invert': true
//                }
//            }
//        }
//    },
//	{
//	    'selector': '#parallaxHeaderOutter',
//	    'properties': {
//	        'x': {
//	            'background-position-x': {
//	                'initial': 50,
//	                'multiplier': 0.02,
//	                'unit': '%'
//	            }
//	        }
//	    }
//	},
//	{
//	    'selector': '#parallaxHeaderInner',
//	    'properties': {
//	        'x': {
//	            'background-position-x': {
//	                'initial': 0,
//	                'multiplier': 0.3
//	            }
//	        }
//	    }
//	}]
//});